package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"topic-chat/api/request"
	"topic-chat/internal/model"
	"topic-chat/pkg"
)

func RegisterUser(c *gin.Context) {
	var req request.RegisterUserForm
	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	user.Mobile = req.Mobile

	err := user.GetByMobileUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}

	if user.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}

	user.Password = pkg.Md5(req.Password)
	user.Name = req.Name
	err = user.RegisterUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "注册成功",
		"data": user.Name,
	})

}

func LoginUser(c *gin.Context) {
	var req request.LoginUserForm
	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	user.Mobile = req.Mobile

	err := user.GetByMobileUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "登陆失败",
			"data": nil,
		})
		return
	}

	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "账号或密码错误",
			"data": nil,
		})
		return
	}

	if user.Password != pkg.Md5(req.Password) {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "账号或密码错误",
			"data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "登陆成功",
		"data": nil,
	})
}
